<template>
  <view class="home">
    <!-- 头部 start -->
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      leftBtnShow="true"
      backgroundImage="linear-gradient(#3388FF, #6197f8)"
      :border="false"
      leftIcon="back"
      color="#fff"
      @clickLeft="clickLeft"
    >
       <view class="uni-title">{{title}}</view>
    </uni-nav-bar>
    <!-- 头部 end -->

    <!-- 内容 start -->
    <view class="content" :style="{height: (offsetHeight-offsetTop-10)+'px'}">
      <view class="form-box">
        <u-form :model="addressForm" ref="addressForm" :rules="addressFormRules" labelWidth="160rpx">
          <u-form-item label="收货人" prop="destName" borderBottom >
            <u-input v-model="addressForm.destName" border="none" placeholder="请填写收货人"/>
          </u-form-item>
          <u-form-item label="手机号码" prop="destMobile" borderBottom>
            <u-input v-model="addressForm.destMobile" border="none" type="number" maxlength="11" placeholder="请填写手机号码"/>
          </u-form-item>
          <u-form-item label="所在地区" prop="companyArea" borderBottom>
            <vvSelectArea :list="areas" v-model="addressForm.companyArea" placeholder="请选择所在区域" @changeLabel="changeLabel"></vvSelectArea>
          </u-form-item>
          <u-form-item label="详细地址" prop="destAddress" borderBottom>
            <u-input v-model="addressForm.destAddress" border="none" placeholder="请填写详细地址"/>
          </u-form-item>
        </u-form>
      </view>
       <view class="form-box flex default-box">
        <view class="left-box">
          <view>设置默认地址</view>  
          <view class="tip">设置默认地址</view>  
        </view>
        <view>
          <u-switch v-model="addressForm.isDefault" @change="switchChange" size="40" active-value='1' inactive-value='0'></u-switch>
        </view>
       </view>
      <view class="btn-bottom">
        <Button size="large" type="primary" @click="createAddress('addressForm')">保存</Button>
      </view>
    </view>
    <!-- 头部信息 start -->
    <!-- 头部信息 end -->
  </view>
</template>

<script>
import hccmStore from "@/common/hccm-store.js"
import mRequest from "@/api/home"
import vvSelectArea from '@/components/vv-select-area/vv-select-area'
import hccmConfig from "@/common/hccm-config.js"
export default {
  components:{vvSelectArea},
  data() {
    const mobileReg = (rule, value, callback) => {
      const mobileReg = /^1[1234567890]\d{9}$/
      if(!value){
        return callback(new Error('手机号不能为空'));
      } else if (!mobileReg.test(value)) {
        return callback(new Error('请输入正确的手机号码'));
      }else{
        callback();
      }
    };
    const companyAreaReg = (rule, value, callback) => {
      if(!value){
        return callback(new Error('省市区不能为空'));
      } else{
        callback();
      }
    };
    return {
      userInfo: hccmStore.getUser(),
      areas: hccmStore.getAreaList(), // 地址list
      addressForm: {
				destName: '', //收货人姓名
				destMobile: '', //收货人手机号
        // companyArea: ["210000", "210400", "210403"],//收货人省名称
        companyArea: [],//收货人省名称
        destProvinceName:'',//省份名称name
        destCityName:'',//城市名称name
        destRegionName:'',//区名称name
        destProvinceId:'',//省份名称Id
        destCityId:'',//城市名称Id
        destRegionId:'',//区名称Id
        destAddress:'',//收货人全地址
        isDefault: '1',
			},
			addressFormRules: {
				destName: {
					type: 'string',
					required: true,
					message: '请填写姓名',
					trigger: ['blur', 'change']
				},
        destMobile:[ { required: true, message: '手机号码不能为空'}, { validator: mobileReg, trigger: ['blur', 'change'] }],
        // destMobile:[ { required: true, message: '手机号码不能为空',trigger: ['blur', 'change']}],
        companyArea:[ { required: true, message: '省市区不能为空'}, { validator: companyAreaReg, trigger: ['blur', 'change'] }],
        destAddress:[ { required: true, message: '详细地址不能为空',trigger: ['blur', 'change']}]
			},
      offsetTop: hccmStore.getOffsetTop(), //安全高度
      offsetHeight:  hccmStore.getOffsetHeight(), //安全高度
      title: '新增编辑收货地址',
      addressJson: '',
      prescriptionId: '',
      hospTotalPrice: '',
      orderId:'',
      hospId: '',
      chooseFlag: false,
      orderFlag: false,
      action: '',
      drugsList:'',
    }
  },
  onLoad(options) {
    console.log('options edit-address',options)
    this.addressId = options.addressId
    this.addressJson = options.addressJson
    this.chooseFlag = options.chooseFlag 
    this.prescriptionId = options.prescriptionId
    this.hospTotalPrice = options.hospTotalPrice  
    this.orderFlag = options.orderFlag 
    this.drugsList = options.drugsList  
    this.action = options.action
    this.orderId = options.orderId
    this.hospId = options.hospId
    if(!hccmStore.getAreaList()){
      this.getArea()
    }
    this.addressId && this.getAddressById(this.addressId)
    console.log(this.prescriptionId,34343)
  },
  onShow() {
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.addressForm.setRules(this.addressFormRules)
  },
  methods: {
    changeLabel(val){
      this.addressForm.destProvinceName = val[0]
      this.addressForm.destCityName = val[1]
      this.addressForm.destRegionName = val[2]
      this.addressForm.destProvinceId = this.addressForm.companyArea[0]
      this.addressForm.destCityId = this.addressForm.companyArea[1]
      this.addressForm.destRegionId = this.addressForm.companyArea[2]
    },
    getAddressById(addressId){
      mRequest.getAddressById({addressId}).then(res=>{
        this.addressForm = JSON.parse(JSON.stringify(res.responseData))
        this.addressForm.companyArea = [res.responseData.destProvinceId,res.responseData.destCityId,res.responseData.destRegionId]
        this.addressForm.isDefault = res.responseData.isDefault?'1':'0'
        console.log(res)
      })
    },
    getArea(){
      mRequest.getArea().then(res=>{
        hccmStore.setAreaList(res.responseData)
        this.areas = hccmStore.getAreaList()
      }).catch(err=>{
        console.log(err)
      })
    },
    createAddress(formName) {
			this.$refs[formName].validate().then(res => {
				// TODO 需要知道是编辑还是新增 
        let params = JSON.parse(JSON.stringify(this.addressForm))
        params.isDefault = Number(this.addressForm.isDefault)
        params.patientMobile = hccmStore.getUserPhone()
        // 如果地址中有省市区的话，就不用拼接到详细地址的bak中了
        this.addressForm.destAddressBak = ''
        if (this.addressForm.destAddress.indexOf(this.addressForm.destProvinceName) >= 0 && this.addressForm.destAddress.indexOf(this.addressForm.destCityName) >= 0 && this.addressForm.destAddress.indexOf(this.addressForm.destRegionName) >= 0) {
          
            this.addressForm.destAddressBak = this.addressForm.destAddress
          } else {
            this.addressForm.destAddressBak = `${this.addressForm.destProvinceName}-${this.addressForm.destCityName}-${this.addressForm.destRegionName}-${this.addressForm.destAddress}`
          }
        params.destAddress = this.addressForm.destAddressBak
        if(this.addressId){
          params.addressId = this.addressId
          mRequest.updateAddress(params).then(res=>{
            if(res.code == 200){
              wx.showToast({
                title: res.message,
                duration: 1000
              })
              setTimeout(() => {
                console.log('chooseFlag=${this.chooseFlag}',this.chooseFlag)
                uni.redirectTo({
                  url: `/pages/address/address-list?addressJson=${this.addressJson}&chooseFlag=${this.chooseFlag}&prescriptionId=${this.prescriptionId}&hospTotalPrice=${this.hospTotalPrice}&hospId=${this.hospId}&orderId=${this.orderId}&orderFlag=${this.orderFlag}&drugsList=${this.drugsList}&action=${this.action}`,
                  success: res => {},
                  fail: () => {},
                  complete: () => {},
                })
              }, 1000);
            }
          }).catch(err=>{
            console.log(err)
          })
        }else{
          console.log(params)
          mRequest.createAddress(params).then(res=>{
            if(res.code == 200){
              wx.showToast({
                title: res.message,
                duration: 1000
              })
              setTimeout(() => {
                uni.navigateTo({
                  url: `/pages/address/address-list?addressJson=${this.addressJson}&chooseFlag=${this.chooseFlag}&prescriptionId=${this.prescriptionId}&hospTotalPrice=${this.hospTotalPrice}&hospId=${this.hospId}&orderId=${this.orderId}&orderFlag=${this.orderFlag}&drugsList=${this.drugsList}&action=${this.action}`,
                  success: res => {},
                  fail: () => {},
                  complete: () => {},
                })
              }, 1000);
            }
          }).catch(err=>{
            console.log(err)
          })
        }
			}).catch(errors => {
				console.log('error submit!!')
        return false
			})
		},
    clickLeft(){
      uni.navigateBack()
    },
    switchChange(e){},
  },
}
</script>

<style lang="scss">
@import "@/static/css/index.scss";
// begin
.home {
  height: 100%;
  overflow: hidden;
  .content{
    box-sizing: border-box;
    overflow: auto;
    padding-bottom: 220rpx;
    background-image: linear-gradient(#6197f8, #f5f5f5, #f5f5f5);
    
    box-sizing: border-box;
    .form-box{
      margin: 30rpx;
      padding: 20rpx;
      background: #fff;
      border-radius: 20rpx;
    }
    .default-box{
      .left-box{
        flex: 1;
        .tip{
          color: #999999;
          font-size: 24rpx;
          padding: 10rpx 0;
        }
      }
    }
  }
}
</style>
